package com.element.security.server.handler;

import com.common.core.exception.code.SecurityErrorCode;
import com.common.core.results.VoidResult;
import com.element.security.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证失败接口
 *
 * @auther zhangwj
 * @date 2021/3/22 下午6:51
 */
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e) throws IOException {
        logger.error("AuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), e);
        VoidResult voidResult;
        if (e instanceof InternalAuthenticationServiceException) {
            voidResult = VoidResult.failed(SecurityErrorCode.A_INTERNAL_AUTHENTICATION_SERVICE_EXCEPTION);
        } else {
            voidResult = VoidResult.failed(SecurityErrorCode.A_CLIENT_AUTHENTICATION_FAILED);
        }
        ResponseUtil.writeJson(response, voidResult);
    }
}
